import requests
import json
import subprocess
from functools import partial
subprocess.Popen = partial(subprocess.Popen, encoding="utf-8")
import execjs


def read_header(page):
    with open("headers加密.js", "r", encoding="utf-8") as f:
        data = f.read()
    js = execjs.compile(data)
    return js.call("result", page)




if __name__ == '__main__':
    page = int(input("请输入要抓哪一页："))
    headers = {
        "Accept": "application/json, text/plain, */*",
        "Accept-Language": "zh-CN,zh;q=0.9",
        "Connection": "keep-alive",
        "Content-Type": "application/json",
        "Origin": "https://ygp.gdzwfw.gov.cn",
        "Referer": "https://ygp.gdzwfw.gov.cn/",
        "Sec-Fetch-Dest": "empty",
        "Sec-Fetch-Mode": "cors",
        "Sec-Fetch-Site": "same-origin",
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
        "X-Dgi-Req-App": "ggzy-portal",
        "sec-ch-ua": "\"Not_A Brand\";v=\"8\", \"Chromium\";v=\"120\", \"Google Chrome\";v=\"120\"",
        "sec-ch-ua-mobile": "?0",
        "sec-ch-ua-platform": "\"Windows\""
    }
    cookies = {
        "_horizon_uid": "52fe4fa5-308b-4676-b664-7ec494dbe41b"
    }
    url = "https://ygp.gdzwfw.gov.cn/ggzy-portal/search/v2/items"
    data = {
        "type": "trading-type",
        "openConvert": False,
        "keyword": "",
        "siteCode": "44",
        "secondType": "A",
        "tradingProcess": "",
        "thirdType": "[]",
        "projectType": "",
        "publishStartTime": "",
        "publishEndTime": "",
        "pageNo": page,
        "pageSize": 10
    }
    result_header = read_header(page)
    print(result_header)
    headers["X-Dgi-Req-Nonce"] = result_header["X-Dgi-Req-Nonce"]
    headers["X-Dgi-Req-Signature"] = result_header["X-Dgi-Req-Signature"]
    headers["X-Dgi-Req-Timestamp"] = str(result_header["X-Dgi-Req-Timestamp"])
    data = json.dumps(data, separators=(',', ':'))
    response = requests.post(url, headers=headers, cookies=cookies, data=data)

    print(response.text)
    print(response)
